$(document).ready(function () {

    bulletinDialog.init();
    bulletinDialog.setSaveButtonHandler(function () {
        if (!$('#form_bulletin_detail').valid())
            return;

        UIkit.modal.confirm('确认保存公告？', saveBulletin);
    });

    $('#btn_add_bulletin').click(function () {
        bulletinDialog.resetDialog();
        $('#bulletin_index')[0].value = '';
        bulletinDialog.showDialog();
    });
    $('#btn_delete_bulletin').click(function () {
        turnToDeleteMode(true);
    });
    $('#btn_complete_deletion').click(function () {
        turnToDeleteMode(false);
    });

    listAllBulletin();
});

var bulletinDialog = {
    init: function() {
        this.validator = $('#form_bulletin_detail').validate({
            rules: {
                'title:string': {
                    required: true,
                    maxlength: 128
                },
                'content:string': {
                    required: true
                }
            },
            messages: {
                'title:string': {
                    required: '此项必填',
                    maxlength: '标题不能超过 128 个字符'
                },
                'content:string': {
                    required: '此项必填'
                }
            },
            errorClass: "uk-text-danger",
            errorPlacement: function (error, element) {
                error.insertAfter(element.parent("div"));
            },
            highlight: function (element, errorClass, validClass) {
                $(element).addClass("uk-form-danger");
            },
            unhighlight: function (element, errorClass, validClass) {
                $(element).removeClass("uk-form-danger");
            }
        });
    },
    setSaveButtonHandler: function (handler) {
        if (handler != null)
            $('#btn_save_bulletin').click(handler);
    },
    enableModification: function (enable) {
        $('#bulletin_content').prop('disabled', !enable);
        $('#bulletin_title').prop('disabled', !enable);
        $('#btn_save_bulletin').prop('disabled', !enable);
    },
    resetDialog: function () {
        this.validator.resetForm();
        this.enableModification(true);
        $('#bulletin_content')[0].value = null;
        $('#bulletin_title')[0].value = null;
        $('#form_bulletin_detail .uk-form-danger').removeClass("uk-form-danger");
    },
    fillUp: function(bulletin) {
        this.resetDialog();
        if (bulletin == null)
            return;

        $('#bulletin_title')[0].value = bulletin.title;
        $('#bulletin_content')[0].value = bulletin.content;
    },
    showDialog: function () {
        UIkit.modal('#bulletin_detail_dialog').show();
    },
    hideDialog: function () {
        UIkit.modal('#bulletin_detail_dialog').hide();
    }
};

var bulletinList = {
    bulletins: [],

    appendBulletin: function (bulletin) {
        if (bulletin != null) {
            this.bulletins.push(bulletin);
            var tableRow = bulletin2TableRow(bulletin, this.bulletins.length);
            $('#tbody_bulletin_list').append(tableRow);
        }
    },
    prependBulletin: function (bulletin) {
        if (bulletin != null) {
            this.bulletins.splice(0, 0, bulletin);
            var tableRow = bulletin2TableRow(bulletin, 1);
            $('#tbody_bulletin_list').prepend(tableRow);
            this.updateTableIndex(1);
        }
    },
    deleteBulletin: function (index) {
        index = parseInt(index);
        if (isNaN(index) || index < 0 || index >= this.bulletins.length)
            return;

        this.bulletins.splice(index, 1);
        $('#tbody_bulletin_list tr:nth-child(' + (index + 1) + ')').remove();
        this.updateTableIndex(index);
    },
    clearLish: function () {
        $('#tbody_bulletin_list tr').remove();
        this.bulletins = [];
    },
    updateTableIndex: function(from) {
        if (from < 0)
            from = 0;
        var rows = $("#tbody_bulletin_list td:first-of-type");
        for (var i = from; i < rows.length; i++) {
            $(rows[i]).text(i + 1);
        }
    }
};

function deleteBulletin() {
    var index = parseInt($(this).parent().prevAll().last().text()) - 1;
    UIkit.modal.confirm('确认删除公告？', function () {
        var bulletin = bulletinList.bulletins[index];
        blockingModal = UIkit.modal.blockUI('正在删除...');
        $.ajax({
            url: '/api/bulletin/' + bulletin.bulletinId,
            type: 'DELETE'
        })
            .done(function () {
                UIkit.notify('删除成功', {status: 'success'});
                bulletinList.deleteBulletin(index);
            })
            .fail(function () {
                UIkit.modal.alert('出现错误，删除失败');
            })
            .always(function () {
                blockingModal.hide();
            })
    });
}

function viewBulletin() {
    var index = parseInt($(this).parent().prevAll().last().text()) - 1;
    var currBulletin = bulletinList.bulletins[index];
    bulletinDialog.fillUp(currBulletin);
    bulletinDialog.showDialog();
    $('#bulletin_index')[0].value = index;
    bulletinDialog.enableModification(false);
}

var blockingModal;
function saveBulletin() {
    var form = $('#form_bulletin_detail');

    var index = $('#bulletin_index')[0].value;
    if (index == null || index === '') {
        blockingModal = UIkit.modal.blockUI('正在提交公告...');
        $.ajax({
            url: '/api/bulletin/publish_bulletin',
            data: form.serializeJSON(),
            type: 'POST',
            dataType: 'json'
        })
            .done(function (bulletin_id) {
                UIkit.notify('成功', {status: 'success'});

                if (bulletin_id != null && !isNaN(bulletin_id)) {
                    $.ajax({
                        url: '/api/bulletin/' + bulletin_id,
                        dataType: 'json'
                    })
                        .done(function (bulletin) {
                            if (bulletin == null) {
                                UIkit.modal.alert('出现未知错误，可尝试刷新页面');
                            } else {
                                bulletinList.prependBulletin(bulletin);
                            }
                            bulletinDialog.hideDialog();
                            blockingModal.hide();
                        })
                        .fail(function () {
                            UIkit.modal.alert('出现错误');
                            blockingModal.hide();
                        })
                }
            })
            .fail(function () {
                UIkit.modal.alert('出现错误');
                blockingModal.hide();
            })
    }
}

function turnToDeleteMode(on) {
    if (on) {
        $('.btn-bulletin-delete').show();
        $('.btn-bulletin-detail').hide();
        $('#btn_add_bulletin').prop('disabled', true);
        $('#btn_delete_bulletin').prop('disabled', true);
        $('#btn_complete_deletion').show();
    } else {
        $('.btn-bulletin-delete').hide();
        $('.btn-bulletin-detail').show();
        $('#btn_add_bulletin').prop('disabled', false);
        $('#btn_delete_bulletin').prop('disabled', false);
        $('#btn_complete_deletion').hide();
    }
}

function bulletin2TableRow(bulletin, index) {
    var detailButton = $('<button class="uk-button uk-button-small btn-bulletin-detail">查看</button>');
    detailButton.click(viewBulletin);


    var deleteButton = $('<button class="uk-button uk-button-small uk-button-danger btn-bulletin-delete" style="display: none">删除</button>');
    deleteButton.click(deleteBulletin);

    var buttonCell = $('<td></td>');
    buttonCell.append(detailButton);
    buttonCell.append(deleteButton);

    var tableRow = $('<tr></tr>')
        .append('<td>' + index + '</td>')
        .append('<td>' + bulletin.title + '</td>')
        .append('<td>' + getBriefContent(bulletin.content) + '</td>')
        .append('<td>' + bulletin.publisher + '</td>')
        .append('<td>' + bulletin.releaseTime + '</td>')
        .append(buttonCell);
    return tableRow;
}

function getBriefContent(content) {
    if (content == null || content.length <= 10)
        return content;

    return content.substr(0, 10) + '...';
}

function listAllBulletin() {
    $.ajax({
        url: '/api/bulletin/list_bulletin',
        type: 'GET',
        dataType: 'json'
    })
        .done(function (data) {
            for (var i = 0; i < data.length; i++) {
                bulletinList.appendBulletin(data[i]);
            }
        })
        .fail(function (data) {
            UIkit.modal.alert('获取公告列表时出现错误。');
        })
}